<?php
class FaceService {
	const SUCCESS = 'success';
	const ERROR = 'error';
	//0审核中 1不通过 
	public $_face = array ("/static/attached/face/1.jpg", "/static/attached/face/2.jpg" );
	//存储头像的路径
	private $_savefacePath = "/static/attached/face/";
	/**
	 * 验证头像
	 * @param int $id
	 * @param String $type
	 */
	public function validFace($id, $type) {
		$face = FaceModel::instance ()->getOneFace ( array ('id' => $id ) );
		$uid = $face ['uid'];
		if ($type == 'pass') {
			//修改头像
			$this->saveFace ( $face ['face'], $uid, 1 );
			//删除申请
			FaceModel::instance ()->delFaceOne ( array ('id' => $id ) );
			return self::SUCCESS;
		} else {
			FaceModel::instance ()->delFaceOne ( array ('id' => $id ) );
			//删除图片
			unlink ( getcwd () . $face ['face'] );
			//并提示没有通过
			$this->saveFace ( $this->_face [1], $uid, 0 );
			return self::ERROR;
		}
	}
	/**
	 * 获取所有提交的头像审核
	 */
	public function getVaildFaceList() {
		return FaceModel::instance ()->getFaceList ();
	}
	
	/**
	 * 二进制流上传头像
	 * @param int $uid
	 * @param String $username
	 */
	public function uploadFace($uid, $username) {
		
		$post_input = 'php://input';
		$dir = date ( "Ym", time () );
		$url_path = $this->_savefacePath . $dir . "/";
		$save_path = getcwd () . $url_path;
		if (! is_dir ( $save_path )) {
			mkdir ( $save_path, 0777 );
		}
		$postdata = file_get_contents ( $post_input );
		if (isset ( $postdata ) && strlen ( $postdata ) > 0) {
			$name = uniqid () . '.jpg';
			$filename = $save_path . $name;
			$handle = fopen ( $filename, 'w+' );
			fwrite ( $handle, $postdata );
			fclose ( $handle );
			if (is_file ( $filename )) {
				$params = array ('face' => $url_path . $name, 'uid' => $uid, 'username' => $username );
				FaceModel::instance ()->addFaceList ( $params );
				$this->saveFace ( $this->_face [0], $uid, 0 );
				// echo 'Image data save successed,file:' . $filename;
				return true;
			} else {
				die ( 'Image upload error!' );
			}
		} else {
			die ( 'Image data not detected!' );
		}
	}

}